import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_levin/model/article.dart';
import 'package:flutter_levin/provider/provider_widget.dart';
import 'package:flutter_levin/provider/view_state_widget.dart';
import 'package:flutter_levin/ui/weight/app_toolbar.dart';
import 'package:flutter_levin/utils/toolbar_utils.dart';
import 'package:flutter_levin/view_model/home_model.dart';
import 'package:logger/logger.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class HomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _HomePageState();
  }
}

class _HomePageState extends State<HomePage>
    with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    var logger = Logger();
    final Brightness brightness = MediaQuery.of(context).platformBrightness;
    bool isDark = brightness == Brightness.dark;
    logger.d('--------------------$isDark');

    ToolbarUtils.setBarStatus(!isDark);
    return Scaffold(
      appBar: ToolBar(
        title: '首页',
        visibilityLeft: false,
      ),
      body: ProviderWidget<HomeModel>(
        model: HomeModel(),
        onModelReady: (model) => model.initData(),
        builder: (context, model, child) {
          if (model.isBusy) {
            return ViewStateBusyWidget();
          } else if (model.isError && model.list.isEmpty) {
            return ViewStateErrorWidget(
              error: model.viewStateError,
              onPressed: model.initData(),
            );
          } else if (model.isEmpty) {
            return ViewStateEmptyWidget(
              onPressed: model.initData(),
            );
          }
          return SmartRefresher(
            controller: model.refreshController,
            onRefresh: model.refresh,
            onLoading: model.loadData,
            enablePullDown: true,
            child: ListView.separated(
                itemCount: model.list.length,
                separatorBuilder: (ctx, index) {
                  return Divider(
                    color: Colors.black26,
                  );
                },
                itemBuilder: (ctx, index) {
                  Article item = model.list[index];
                  return Text(
                    item.title,
                    style: TextStyle(color: Theme.of(context).accentColor),
                  );
                }),
          );
        },
      ),
    );
  }
}
